<template>
    <div>
        <div ref="refChart" style="width: 100%;height:15.625rem;"></div>
    </div>
</template>
  
<script setup lang="ts">
import {onUnmounted, onMounted,markRaw, ref} from 'vue';
import * as echarts from 'echarts';
import {RequestStatisticGetCarNumByType} from '@/api/path/index.js';
type EChartsOption = echarts.EChartsOption;
const refChart = ref();
const chartInstance = ref();
const chartData = ref([]);
// 获取接口数据
const getData = () => {
  return new Promise((resolve, reject) => {
    RequestStatisticGetCarNumByType()
      .then((res: any) => {
        chartData.value = res.resultObj;
        resolve(res.resultObj);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};
onMounted(async () => {
  await getData();
  // 图表初始化
  initChart();
  // 调用Echarts图表自适应方法
  screenAdapter();
  // Echarts图表自适应
  window.addEventListener('resize', screenAdapter);
});

const initChart = () => {
  chartInstance.value =markRaw(echarts.init(refChart.value)) ;
  const initOption: EChartsOption = {
    grid: {
      left: '3%',
      right: '3%',
      bottom: '4%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none'
      },
      formatter: function (params) {
        return params[0].name + ': ' + params[0].value;
      }
    },
    xAxis: {
      data: chartData.value.name,
      axisTick: { show: false },
      axisLine: { show: false },
      axisLabel: {
        color: '#767881'
      }
    },
    yAxis: {
      // splitLine: { show: false },
      // axisTick: { show: false },
      // axisLine: { show: false },
      // axisLabel: { show: false }
    },
    color: ['#165dff'],
    series: [
      {
        name: 'hill',
        type: 'pictorialBar',
        barCategoryGap: '-0%',
        symbol: 'path://M0,10 L10,10 C5.5,10 5.5,5 5,0 C4.5,5 4.5,10 0,10 z',
        itemStyle: {
          opacity: 0.5
        },
        emphasis: {
          itemStyle: {
            opacity: 1
          }
        },
        data:  chartData.value.value,
        z: 10
      }
    ]
  };
  // 图表初始化配置
  chartInstance.value?.setOption(initOption);
};
const screenAdapter = () => {
  // 手动的调用图表对象的resize 才能产生效果
  chartInstance.value.resize({width:'auto', animation: { duration: 300 } });
};
onUnmounted(() => {
  // 销毁Echarts图表
  chartInstance.value.dispose();
  chartInstance.value = null;
  // Echarts图表自适应销毁
  window.removeEventListener('resize', screenAdapter);
});
</script>
<style lang="scss" scoped></style>